package top.aigoo.project01.config.web;

import javax.swing.border.Border;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.google.code.kaptcha.servlet.KaptchaServlet;

import top.aigoo.project01.interceptor.shop.ShopLoginInterceptor;
import top.aigoo.project01.interceptor.shop.ShopPermissionInterceptor;

/**
 * 开启Mvc，自动注入spring容器， WebMvcConfigurerAdapter:配置视图解析器
 * 当一个类实现这个接口ApplicationContextAware 之后， 这个类就可以方便的获得ApplicationContext中的所有bean
 */
@Configuration
//等价于<mvc:annotation-driven/>
@EnableWebMvc

public class MvcConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware {
	// Spring容器
	private ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext = applicationContext;
	}

	/**
	 * 静态资源配置 当url中含有/upload/就解析到后面那个地址
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

		String os = System.getProperty("os.name");

		if (os.toLowerCase().startsWith("win")) { // 如果是Windows系统
			registry.addResourceHandler("/upload/**")
					// /upload/**表示在磁盘upload目录下的所有资源会被解析为以下的路径
					//
					.addResourceLocations("file:G:/baidu/project01_o2o/images/upload/")// 图片
					.addResourceLocations("classpath:/META-INF/resources/"); // swagger2页面
		} else { // linux 和mac
			registry.addResourceHandler("/upload/**").addResourceLocations("file:/home/oyshuo/project01_o2o/images/"); // 媒体资源
		}

		// registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
		// registry.addResourceHandler("/upload/**").addResourceLocations("file:G:/baidu/project01_o2o/images/upload/");
	}

	/**
	 * 定义默认的请求处理器
	 */
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

	/**
	 * 创建viewResolver
	 */
	@Bean(name = "viewResolver")
	public ViewResolver createViewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		// 设置Spring容器
		viewResolver.setApplicationContext(this.applicationContext);
		// 取消缓存
		viewResolver.setCache(false);
		// 设置解析的前缀
		viewResolver.setPrefix("/WEB-INF/html/");
		// 设置解析的后缀
		viewResolver.setSuffix(".html");
		return viewResolver;
	}

	/**
	 * 创建添加文件上传解析器
	 */

	@Bean(name = "multipartResolver")
	public MultipartResolver createCommonsMultipartResolver() {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
		// 默认编码
		multipartResolver.setDefaultEncoding("utf-8");
		// 最大上传限制 单位字节 1024*1024*20 20mb
		multipartResolver.setMaxUploadSize(20971520);
		// 最大上传内存 单位字节 1024*1024*20 20mb
		multipartResolver.setMaxInMemorySize(20971520);
		return multipartResolver;
	}

	@Value("${kaptcha.border}")
	private String border;

	@Value("${kaptcha.textproducer.font.color}")
	private String fcolor;

	@Value("${kaptcha.image.width}")
	private String width;

	@Value("${kaptcha.textproducer.char.string}")
	private String cString;

	@Value("${kaptcha.image.height}")
	private String height;

	@Value("${kaptcha.textproducer.font.size}")
	private String fsize;

	@Value("${kaptcha.textproducer.font.names}")
	private String fnames;

	@Value("${kaptcha.noise.color}")
	private String nColor;

	@Value("${kaptcha.textproducer.char.length}")
	private String clength;

	/**
	 * 由于web.xml不生效了，需要在这里配置Kaptcha验证码servlet
	 */
	@Bean
	public ServletRegistrationBean<KaptchaServlet> servletRegisterBean() {
		ServletRegistrationBean<KaptchaServlet> servlet = new ServletRegistrationBean<KaptchaServlet>(
				new KaptchaServlet(), "/Kaptcha");
		servlet.addInitParameter("kaptcha.border", border);// 无边框
		servlet.addInitParameter("kaptcha.textproducer.font.color", fcolor);// 字体颜色
		servlet.addInitParameter("kaptcha.image.width", width);// 图片宽度
		servlet.addInitParameter("kaptcha.textproducer.char.string", cString);// 使用哪些字符生成验证码
		servlet.addInitParameter("kaptcha.image.height", height);// 图片高度
		servlet.addInitParameter("kaptcha.textproducer.font.size", fsize);// 字体大小
		servlet.addInitParameter("kaptcha.textproducer.font.names", fnames);// 使用哪些字体
		servlet.addInitParameter("kaptcha.noise.color", nColor);// 干扰线的颜色
		servlet.addInitParameter("kaptcha.textproducer.char.length", clength);// 字符个数
		return servlet;
	}

	/**
	 * 添加拦截器配置
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		String interceptPath = "/shopadmin/**";
		// 注册拦截器
		InterceptorRegistration loginIR = registry.addInterceptor(new ShopLoginInterceptor());
		// 配置拦截的路径
		loginIR.addPathPatterns(interceptPath);

		// 2.注册其他拦截器
		InterceptorRegistration permissionIR = registry.addInterceptor(new ShopPermissionInterceptor());
		// 配置拦截的路径
		permissionIR.addPathPatterns(interceptPath);

		// 3配置不拦截的路径
		/** shop list page */
		permissionIR.excludePathPatterns("/shopadmin/shoplist");
		permissionIR.excludePathPatterns("/shopadmin/getshoplist");

		/** shop register page */
		permissionIR.excludePathPatterns("/shopadmin/getshopinitinfo");
		permissionIR.excludePathPatterns("/shopadmin/registershop");
		permissionIR.excludePathPatterns("/shopadmin/shopoperation");

		/** shop manage page */
		permissionIR.excludePathPatterns("/shopadmin/shopmanagement");
		permissionIR.excludePathPatterns("/shopadmin/getshopmanagementinfo");
	}

}
